package br.com.sig.presentation.converter;

import javax.enterprise.context.RequestScoped;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.convert.Converter;
import javax.faces.convert.FacesConverter;

/**
 * Converter CPF
 *
 */
@FacesConverter(value = "cpfConverter")
@RequestScoped
public class CpfConverter implements Converter {

	public Object getAsObject(FacesContext context, UIComponent ui, String value) {
		if (value == null || (value.trim().length() == 0)) {
			return value;
		}

		String[] str = value.split("\\.|-");
		StringBuilder cpf = new StringBuilder();
		cpf.append(str[0] + str[1] + str[2] + str[3]);
		return cpf.toString();
	}

	public String getAsString(FacesContext context, UIComponent ui, Object obj) {
		if (obj == null) {
			return null;
		}

		String str = (String) obj;
		if (str.length() == 11) {
			str = str.substring(0, 3) + "." + str.substring(3, 6) + "." + str.substring(6, 9) + "-"
					+ str.substring(9, 11);
		}

		return str;
	}

}